<template>
    <div class="app-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="报表类型">
                    <el-select v-model="searchForm.reportType" placeholder="请选择报表类型" @change="handleReportTypeChange" style="width: 300px;">
                        <el-option label="合格率日报" value="dailyPassRate" />
                        <el-option label="合格率月报" value="monthlyPassRate" />
                        <el-option label="均值报表" value="avgReport" />
                        <el-option label="实时报表" value="realtimeReport" />
                    </el-select>
                </el-form-item>

                <el-form-item label="时间维度">
                    <el-select v-model="searchForm.timeDimension" placeholder="请选择时间维度" style="width: 300px;"
                        @change="handleTimeDimensionChange">
                        <el-option label="日维度" :value="1" />
                        <el-option label="月维度" :value="2" />
                        <el-option label="年维度" :value="3" />
                    </el-select>
                </el-form-item>

                <el-form-item label="时间范围">
                    <el-date-picker v-if="searchForm.timeDimension === 1" v-model="searchForm.time" type="date" style="width: 300px;"
                        placeholder="选择日期" value-format="YYYY-MM-DD" />
                    <el-date-picker v-if="searchForm.timeDimension === 2" v-model="searchForm.time" type="month" style="width: 300px;"
                        placeholder="选择月份" value-format="YYYY-MM" />
                    <el-date-picker v-if="searchForm.timeDimension === 3" v-model="searchForm.time" type="year" style="width: 300px;"
                        placeholder="选择年份" value-format="YYYY" />
                </el-form-item>

                <el-form-item label="监测量">
                    <el-select v-model="searchForm.monitorCodes" placeholder="请选择监测量" multiple collapse-tags
                        collapse-tags-tooltip style="width: 300px;">
                        <el-option v-for="item in monitoringOptions" :key="item.monitorCode" :label="item.monitorName"
                            :value="item.monitorCode" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button type="success" @click="handleExport">导出Excel</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 数据展示区 -->
        <div class="data-container">
            <!-- 合格率日报 -->
            <div v-if="searchForm.reportType === 'dailyPassRate'">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">总样本数</div>
                                <div class="stat-value">{{ dailyStats.totalSamples?.toLocaleString() || '0' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="8">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">合格样本数</div>
                                <div class="stat-value">{{ dailyStats.passSamples?.toLocaleString() || '0' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="8">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">平均合格率</div>
                                <div class="stat-value" :class="getRateClass(dailyStats.avgPassRate)">
                                    {{ dailyStats.avgPassRate ? (dailyStats.avgPassRate * 100).toFixed(2) + '%' : '0%'
                                    }}
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>

                <el-card class="mt-2">
                    <el-table :data="dailyPassRateData" v-loading="loading" border stripe>
                        <el-table-column prop="bucket" label="日期" align="center"/>
                        <el-table-column prop="totalSamples" label="总样本数" align="center">
                            <template #default="{ row }">
                                {{ row.totalSamples?.toLocaleString() || '0' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="passSamples" label="合格样本数" align="center">
                            <template #default="{ row }">
                                {{ row.passSamples?.toLocaleString() || '0' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="passRate" label="合格率" align="center">
                            <template #default="{ row }">
                                <el-tag :type="getRateType(row.passRate)">
                                    {{ row.passRate ? (row.passRate * 100).toFixed(2) + '%' : '0%' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center">
                            <template #default="{ row }">
                                <el-tag :type="getStatusType(row.passRate)">
                                    {{ getStatusText(row.passRate) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </div>

            <!-- 合格率月报 -->
            <div v-if="searchForm.reportType === 'monthlyPassRate'">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">总样本数</div>
                                <div class="stat-value">{{ monthlyStats.totalSamples?.toLocaleString() || '0' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">合格样本数</div>
                                <div class="stat-value">{{ monthlyStats.passSamples?.toLocaleString() || '0' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">平均合格率</div>
                                <div class="stat-value" :class="getRateClass(monthlyStats.avgPassRate)">
                                    {{ monthlyStats.avgPassRate ? (monthlyStats.avgPassRate * 100).toFixed(2) + '%' :
                                    '0%' }}
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">监测月份</div>
                                <div class="stat-value">{{ monthlyPassRateData.length }}</div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>

                <el-card class="mt-2">
                    <el-table :data="monthlyPassRateData" v-loading="loading" border stripe>
                        <el-table-column prop="bucket" label="月份" align="center" />
                        <el-table-column prop="totalSamples" label="总样本数" align="center">
                            <template #default="{ row }">
                                {{ row.totalSamples?.toLocaleString() || '0' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="passSamples" label="合格样本数" align="center">
                            <template #default="{ row }">
                                {{ row.passSamples?.toLocaleString() || '0' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="passRate" label="合格率" align="center">
                            <template #default="{ row }">
                                <el-tag :type="getRateType(row.passRate)">
                                    {{ row.passRate ? (row.passRate * 100).toFixed(2) + '%' : '0%' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="环比" align="center">
                            <template #default="{ row }">
                                <span :class="getChainRatioClass(row.chainRatio)">
                                    {{ row.chainRatio > 0 ? '+' : '' }}{{ (row.chainRatio * 100).toFixed(2) }}%
                                </span>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>

            </div>

            <!-- 均值报表 -->
            <div v-if="searchForm.reportType === 'avgReport'">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">平均压力值</div>
                                <div class="stat-value">{{ avgStats.avgValue?.toFixed(3) || '0.000' }} MPa</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">数据点数</div>
                                <div class="stat-value">{{ avgStats.dataPoints?.toLocaleString() || '0' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">时间范围</div>
                                <div class="stat-value">{{ avgStats.timeRange || '-' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">波动率</div>
                                <div class="stat-value">{{ avgStats.fluctuationRate?.toFixed(2) || '0.00' }}%</div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>

                <el-card class="mt-2">
                    <el-table :data="avgReportData" v-loading="loading" border stripe>
                        <el-table-column prop="bucket" label="时间桶" align="center" />
                        <el-table-column prop="avgVal" label="平均压力值" align="center">
                            <template #default="{ row }">
                                {{ row.avgVal?.toFixed(3) || '0.000' }} MPa
                            </template>
                        </el-table-column>
                        <el-table-column prop="cnt" label="数据点数" align="center">
                            <template #default="{ row }">
                                {{ row.cnt?.toLocaleString() || '0' }}
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center">
                            <template #default="{ row }">
                                <el-tag :type="getPressureStatusType(row.avgVal)">
                                    {{ getPressureStatus(row.avgVal) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="波动率" align="center">
                            <template #default="{ row }">
                                {{ row.fluctuationRate?.toFixed(2) || '0.00' }}%
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </div>

            <!-- 实时报表 -->
            <div v-if="searchForm.reportType === 'realtimeReport'">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">监测点数量</div>
                                <div class="stat-value">{{ realtimeStats.monitorCount || '0' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="4">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">平均压力值</div>
                                <div class="stat-value">{{ realtimeStats.avgPressure?.toFixed(3) || '0.000' }} MPa</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="4">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">平均合格率</div>
                                <div class="stat-value" :class="getRateClass(realtimeStats.avgPassRate)">
                                    {{ realtimeStats.avgPassRate ? (realtimeStats.avgPassRate * 100).toFixed(2) + '%' :
                                    '0%' }}
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="4">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">正常监测点</div>
                                <div class="stat-value normal">{{ realtimeStats.normalCount || '0' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="4">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">异常监测点</div>
                                <div class="stat-value abnormal">{{ realtimeStats.abnormalCount || '0' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="4">
                        <el-card>
                            <div class="stat-card">
                                <div class="stat-title">最新时间</div>
                                <div class="stat-value">{{ realtimeStats.latestTime || '-' }}</div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>

                <el-card class="mt-2">
                    <el-table :data="realtimeReportData" v-loading="loading" border stripe>
                        <el-table-column prop="monitorCode" label="监测量编码" align="center"/>
                        <el-table-column prop="monitorName" label="监测量名称" align="center"/>
                        <el-table-column prop="avgVal" label="平均压力" align="center">
                            <template #default="{ row }">
                                {{ row.avgVal?.toFixed(3) || '0.000' }} MPa
                            </template>
                        </el-table-column>
                        <el-table-column prop="minVal" label="最小压力" align="center">
                            <template #default="{ row }">
                                {{ row.minVal?.toFixed(3) || '0.000' }} MPa
                            </template>
                        </el-table-column>
                        <el-table-column prop="maxVal" label="最大压力" align="center">
                            <template #default="{ row }">
                                {{ row.maxVal?.toFixed(3) || '0.000' }} MPa
                            </template>
                        </el-table-column>
                        <el-table-column prop="cntTotal" label="总样本数" align="center">
                            <template #default="{ row }">
                                {{ row.cntTotal?.toLocaleString() || '0' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="cntPass" label="合格样本数" align="center">
                            <template #default="{ row }">
                                {{ row.cntPass?.toLocaleString() || '0' }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="passRate" label="合格率" align="center">
                            <template #default="{ row }">
                                <el-tag :type="getRateType(row.passRate)">
                                    {{ row.passRate ? (row.passRate * 100).toFixed(2) + '%' : '0%' }}
                                </el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="状态" align="center">
                            <template #default="{ row }">
                                <el-tag :type="getRealtimeStatusType(row)">
                                    {{ getRealtimeStatus(row) }}
                                </el-tag>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import Echarts from '@/components/ECharts'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()

// API引入
import {
    getMonitoringList,
    getDailyPassRate,
    getMonthlyPassRate,
    getAvgReport,
    getRealtimeReport
} from '@/api/dispatch/analyze/pressure_report'

// 搜索表单
const searchForm = reactive({
    reportType: 'dailyPassRate',
    timeDimension: 1,
    time: dayjs().format('YYYY-MM-DD'),
    monitorCodes: []
})

// 加载状态
const loading = ref(false)

// 数据存储
const monitoringOptions = ref([])
const dailyPassRateData = ref([])
const monthlyPassRateData = ref([])
const avgReportData = ref([])
const realtimeReportData = ref([])

// 初始化数据
onMounted(() => {
    fetchMonitoringList()
    fetchReportData()
})

// 获取监测量列表
const fetchMonitoringList = async () => {
    try {
        const res = await getMonitoringList()
        monitoringOptions.value = res.data || []
    } catch (error) {
        console.error('获取监测量列表失败:', error)
        ElMessage.error('获取监测量列表失败')
    }
}

// 获取报表数据
const fetchReportData = async () => {
    try {
        loading.value = true

        const params = {
            timeDimension: searchForm.timeDimension,
            time: searchForm.time,
            monitorCodes: searchForm.monitorCodes.join(',')
        }

        switch (searchForm.reportType) {
            case 'dailyPassRate':
                const dailyRes = await getDailyPassRate(params)
                dailyPassRateData.value = dailyRes.data || []
                break
            case 'monthlyPassRate':
                const monthlyRes = await getMonthlyPassRate(params)
                monthlyPassRateData.value = monthlyRes.data || []
                break
            case 'avgReport':
                const avgRes = await getAvgReport(params)
                avgReportData.value = avgRes.data || []
                break
            case 'realtimeReport':
                const realtimeRes = await getRealtimeReport(params)
                realtimeReportData.value = realtimeRes.data || []
                break
        }

        ElMessage.success('数据加载成功')
    } catch (error) {
        console.error('获取报表数据失败:', error)
        ElMessage.error('获取报表数据失败')
    } finally {
        loading.value = false
    }
}

// 处理报表类型变化
const handleReportTypeChange = (type) => {
    // 根据报表类型调整时间维度默认值
    switch (type) {
        case 'dailyPassRate':
            searchForm.timeDimension = 1
            searchForm.time = dayjs().format('YYYY-MM-DD')
            break
        case 'monthlyPassRate':
            searchForm.timeDimension = 2
            searchForm.time = dayjs().format('YYYY-MM')
            break
        case 'avgReport':
            searchForm.timeDimension = 1
            searchForm.time = dayjs().format('YYYY-MM-DD')
            break
        case 'realtimeReport':
            searchForm.timeDimension = 1
            searchForm.time = dayjs().format('YYYY-MM-DD')
            break
    }
    fetchReportData()
}

// 处理时间维度变化
const handleTimeDimensionChange = (dimension) => {
    // 根据时间维度调整时间格式
    switch (dimension) {
        case 1:
            searchForm.time = dayjs().format('YYYY-MM-DD')
            break
        case 2:
            searchForm.time = dayjs().format('YYYY-MM')
            break
        case 3:
            searchForm.time = dayjs().format('YYYY')
            break
    }
    fetchReportData()
}

// 处理查询
const handleSearch = () => {
    fetchReportData()
}

// 重置搜索
const resetSearch = () => {
    searchForm.reportType = 'dailyPassRate'
    searchForm.timeDimension = 1
    searchForm.time = dayjs().format('YYYY-MM-DD')
    searchForm.monitorCodes = []
    fetchReportData()
}

// 导出Excel
const handleExport = () => {
    const params = {
        timeDimension: searchForm.timeDimension,
        time: searchForm.time,
        monitorCodes: searchForm.monitorCodes.join(',')
    }

    let exportUrl = ''
    let fileName = ''

    switch (searchForm.reportType) {
        case 'dailyPassRate':
            exportUrl = '/dispatch/pressure/report/daily-pass-rate/export'
            fileName = `合格率日报_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
            break
        case 'monthlyPassRate':
            exportUrl = '/dispatch/pressure/report/monthly-pass-rate/export'
            fileName = `合格率月报_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
            break
        case 'avgReport':
            exportUrl = '/dispatch/pressure/report/avg/export'
            fileName = `均值报表_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
            break
        case 'realtimeReport':
            exportUrl = '/dispatch/pressure/report/realtime/export'
            fileName = `实时报表_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`
            break
    }

    // 使用proxy.download进行导出
    proxy.download(exportUrl, params, fileName)
    ElMessage.success('导出任务已开始')
}

// 计算属性 - 统计数据
const dailyStats = computed(() => {
    const data = dailyPassRateData.value
    const totalSamples = data.reduce((sum, item) => sum + (item.totalSamples || 0), 0)
    const passSamples = data.reduce((sum, item) => sum + (item.passSamples || 0), 0)
    const avgPassRate = totalSamples > 0 ? passSamples / totalSamples : 0

    return {
        totalSamples,
        passSamples,
        avgPassRate
    }
})

const monthlyStats = computed(() => {
    const data = monthlyPassRateData.value
    const totalSamples = data.reduce((sum, item) => sum + (item.totalSamples || 0), 0)
    const passSamples = data.reduce((sum, item) => sum + (item.passSamples || 0), 0)
    const avgPassRate = totalSamples > 0 ? passSamples / totalSamples : 0

    return {
        totalSamples,
        passSamples,
        avgPassRate
    }
})

const avgStats = computed(() => {
    const data = avgReportData.value
    const avgValue = data.length > 0 ? data.reduce((sum, item) => sum + (item.avgVal || 0), 0) / data.length : 0
    const dataPoints = data.reduce((sum, item) => sum + (item.cnt || 0), 0)
    const timeRange = data.length > 0 ? `${data[0].bucket} ~ ${data[data.length - 1].bucket}` : '-'

    return {
        avgValue,
        dataPoints,
        timeRange,
        fluctuationRate: 0 // 这里可以根据实际数据计算波动率
    }
})

const realtimeStats = computed(() => {
    const data = realtimeReportData.value
    const monitorCount = data.length
    const avgPressure = data.length > 0 ? data.reduce((sum, item) => sum + (item.avgVal || 0), 0) / data.length : 0
    const avgPassRate = data.length > 0 ? data.reduce((sum, item) => sum + (item.passRate || 0), 0) / data.length : 0
    const normalCount = data.filter(item => (item.passRate || 0) >= 0.95).length
    const abnormalCount = data.filter(item => (item.passRate || 0) < 0.95).length
    const latestTime = data.length > 0 ? formatDateTime(data[0].tsHour) : '-'

    return {
        monitorCount,
        avgPressure,
        avgPassRate,
        normalCount,
        abnormalCount,
        latestTime
    }
})

// 工具函数
const getRateType = (rate) => {
    if (!rate) return 'info'
    if (rate >= 0.95) return 'success'
    if (rate >= 0.90) return 'warning'
    return 'danger'
}

const getRateClass = (rate) => {
    if (!rate) return ''
    if (rate >= 0.95) return 'rate-high'
    if (rate >= 0.90) return 'rate-medium'
    return 'rate-low'
}

const getStatusType = (rate) => {
    if (!rate) return 'info'
    if (rate >= 0.95) return 'success'
    if (rate >= 0.90) return 'warning'
    return 'danger'
}

const getStatusText = (rate) => {
    if (!rate) return '未知'
    if (rate >= 0.95) return '优秀'
    if (rate >= 0.90) return '良好'
    if (rate >= 0.80) return '一般'
    return '较差'
}

const getPressureStatusType = (pressure) => {
    if (!pressure) return 'info'
    // 这里可以根据实际业务逻辑调整压力状态判断
    if (pressure >= 0.5 && pressure <= 1.0) return 'success'
    if (pressure >= 0.3 && pressure < 0.5) return 'warning'
    return 'danger'
}

const getPressureStatus = (pressure) => {
    if (!pressure) return '未知'
    if (pressure >= 0.5 && pressure <= 1.0) return '正常'
    if (pressure >= 0.3 && pressure < 0.5) return '偏低'
    if (pressure > 1.0) return '偏高'
    return '异常'
}

const getRealtimeStatusType = (row) => {
    if (!row.passRate) return 'info'
    if (row.passRate >= 0.95) return 'success'
    if (row.passRate >= 0.90) return 'warning'
    return 'danger'
}

const getRealtimeStatus = (row) => {
    if (!row.passRate) return '未知'
    if (row.passRate >= 0.95) return '正常'
    if (row.passRate >= 0.90) return '注意'
    return '异常'
}

const getChainRatioClass = (ratio) => {
    if (ratio > 0) return 'text-success'
    if (ratio < 0) return 'text-danger'
    return 'text-info'
}

const formatDateTime = (datetime) => {
    if (!datetime) return '-'
    return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
}
</script>

<style scoped lang="scss">
.app-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 15px;
}

.data-container {
    margin-top: 20px;
}

.stat-card {
    text-align: center;
    padding: 20px 0;
}

.stat-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 10px;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #409eff;

    &.rate-high {
        color: #67c23a;
    }

    &.rate-medium {
        color: #e6a23c;
    }

    &.rate-low {
        color: #f56c6c;
    }

    &.normal {
        color: #67c23a;
    }

    &.abnormal {
        color: #f56c6c;
    }
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.data-count {
    font-size: 14px;
    color: #666;
}

.text-success {
    color: #67c23a;
}

.text-danger {
    color: #f56c6c;
}

.text-info {
    color: #909399;
}

.mt-2 {
    margin-top: 20px;
}

:deep(.el-table) {
    margin-top: 0;
}

:deep(.el-card) {
    margin-bottom: 20px;
}

:deep(.el-card):last-child {
    margin-bottom: 0;
}

@media (max-width: 768px) {
    .search-form {
        flex-direction: column;
        align-items: stretch;
    }

    .search-form .el-form-item {
        width: 100%;
        margin-right: 0;
    }

    .table-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;
    }
}
</style>